package web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import model.Address;
import db.ImbiConnection;

public class AddressParser {
	public static ArrayList<Address> parse(HttpServletRequest request){
		ArrayList<Address> list = new ArrayList<Address>();
		HashMap<Integer, Address> hash = new HashMap<Integer, Address>();
				
		Map<String,String[]> map = request.getParameterMap();
		Set<Entry<String, String[]>> entryset = map.entrySet();
		for(Entry<String, String[]> entry : entryset){
			try{
				String[] key = entry.getKey().split("_");
				Integer addressId = Integer.parseInt(key[0]);
				String type = key[1];				
				if(!hash.containsKey(addressId) && addressId != 0){
					Address found = ImbiConnection.getAddressDAO().find(addressId);
					if(found == null) continue;					
					hash.put(addressId, found);
				} 
				Address a;
				if(addressId == 0){ 
					if(!hash.containsKey(0)){
						a= new Address(addressId, 0, 0, 0, null, null, null, null, null);
						hash.put(0, a);
					} 
					a = hash.get(0);										
				} else a = hash.get(addressId);
				if(type.equalsIgnoreCase("street")) a.setStreetAddress(entry.getValue()[0]);
				else if(type.equalsIgnoreCase("country")) a.setCountry(entry.getValue()[0]);
				else if(type.equalsIgnoreCase("county")) a.setCounty(entry.getValue()[0]);
				else if(type.equalsIgnoreCase("town")) a.setTownVillage(entry.getValue()[0]);
				else if(type.equalsIgnoreCase("zipcode")) a.setZipcode(entry.getValue()[0]);
				else if(type.equalsIgnoreCase("addresstype")) a.setAddressType(Integer.parseInt(entry.getValue()[0]));		
				else if(type.equalsIgnoreCase("subject")) a.setSubject(Integer.parseInt(entry.getValue()[0]));
				else if(type.equalsIgnoreCase("subjecttype")) a.setSubjectType(Integer.parseInt(entry.getValue()[0]));
						
			} catch(Exception e){ }
		}		
		for(Entry<Integer, Address> entry: hash.entrySet()){
			list.add(entry.getValue());
		}
		return list;
	}
}
